package com.hnkywl.sts.service.sys;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.hnkywl.sts.dao.sys.WebServiceLogQueryDao;
import com.hnkywl.sts.entity.base.WebserviceLog;
import com.hnkywl.sts.util.BaseUtils;
import net.ruixin.orm.hibernate.Page;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: ccr
 * Date: 13-9-2
 * Time: 上午10:40
 * To change this template use File | Settings | File Templates.
 */
@Service
public class WebServiceLogQueryService {

    private WebServiceLogQueryDao webServiceLogQueryDao;

    public String findLog(String clazz, String method, String type, String paramData, String resultData, String exception, Date datetimeStart, Date datetimeEnd, int pageNo, int pageSize) {
        Page page = webServiceLogQueryDao.findLog(clazz, method, type, paramData, resultData, exception, datetimeStart, datetimeEnd, pageNo, pageSize);
        List<WebserviceLog> result = page.getResult();
        StringBuffer json = new StringBuffer();
        for (WebserviceLog log : result) {
            String parameterData = StringEscapeUtils.escapeXml(StringUtils.substring(log.getParameterData(), 0, 20));
            json.append("{\"id\":" + log.getId());
            json.append(",\"clazz\":\"" + log.getClazz() + "\"");
            json.append(",\"method\":\"" + log.getMethod() + "\"");
            json.append(",\"type\":\"" + log.getType() + "\"");
            json.append(",\"parameterData\":\"" + (parameterData == null ? parameterData : parameterData.replaceAll("[\\t\\n\\r]","")) + "\"");
            json.append(",\"returnData\":\"" + StringEscapeUtils.escapeXml(StringUtils.substring(log.getReturnData(), 0, 20)) + "\"");
            json.append(",\"time\":\"" + log.getTime() + "\"");
            json.append(",\"clientIP\":\"" + log.getClientIP() + "\"");
            json.append(",\"exception\":\"" + StringEscapeUtils.escapeXml(StringUtils.substring(log.getException(), 0, 20)) + "\"},");
        }
        return "{\"total\":" + page.getTotalCount() + ",\"rows\":[" + (json.length() == 0 ? "" : json.toString().substring(0, json.length() - 1)) + "]}";
    }

    public String findDetail(Long id, String filedName) {
        return webServiceLogQueryDao.findDetail(filedName, id);
    }

    @Autowired
    public void setWebServiceLogQueryDao(WebServiceLogQueryDao webServiceLogQueryDao) {
        this.webServiceLogQueryDao = webServiceLogQueryDao;
    }
}
